import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import * as apis from "@/api/user";

import { getToken, setToken, removeToken } from "@/utils/token-utils";
import type { IUserInfo } from "@/api/user";

interface IState {
  token: string;
  userInfo: IUserInfo;
}

export const useUserStore = defineStore<string, IState, any, any>("user", {
  state() {
    return {
      // 用户 token
      token: getToken() || "",
      userInfo: {
        name: "",
        avatar: "",
        buttons: [],
        roles: [],
        routes: [],
      },
    };
  },

  actions: {
    async login(username: string, password: string) {
      try {
        const res = await apis.login(username, password);
        this.token = res.token;
        setToken(this.token);
      } catch (e) {
        ElMessage.error("请求错误1");
      }
    },

    async getMine() {
      try {
        const res = await apis.getName();
        this.userInfo = { ...res };
      } catch (e) {
        ElMessage.error("请求错误2");
        this.clearUserInfo();
        return Promise.reject(e);
      }
    },
    async reset() {
      try {
        // 调用后端接口退出
        await apis.requestLogout();
        // 前端也要清除和用户相关的数据
        this.clearUserInfo();
      } catch (e) {}
    },

    clearUserInfo() {
      this.token = "";
      this.userInfo = {
        name: "",
        avatar: "",
        routes: [],
        buttons: [],
        roles: [],
      };
      removeToken();
    },
  },
});
